import Cache from '@/utils/cache';
import {CART_INFO} from '@/config/cache';
import store from '@/store';


class Cart {
	
	constructor(handler) {
	    
	}
	
	/**
	 * 更新购物车信息
	 * type:del 删除id为**的一条；add 添加一条；
	 * idParam：商品id
	 * countParam ：添加到购物车的商品数量
	 */
	updateCart(type,idParam,countParam = 0){
		// store.commit("CLEAR_CARTINFO");
		let cartInfoCache = store.state.app.cartInfo || [];
		console.log('缓存里的购物车信息',cartInfoCache);
		
		let cartArr = [];
		//浅复制实现clone数组，防止提示不能在mutation函数外修改vuex中存储的值
		Object.assign(cartArr,cartInfoCache);
		let id = idParam;
		let count = parseInt(countParam);
		let cart = {};
		cart.good_id = id;
		cart.good_count = count;
		if(type == 'del'){
			cartArr = this.delArr(cartArr,idParam);
		}else{
			cartArr = this.addArr(cartArr,idParam,count,cart);
		}
		
		
		console.log('输入的id====：',id,' 输入的数量====：',count)
		console.log('更新后的购物车信息',cartArr);
		store.commit("UPDATE_CARTINFO", cartArr);
	}
	//添加一条
	addArr(cartArr,idParam,count,cart){
		let isExsit = false;
		if (cartArr instanceof Array) {
			for (let i = 0; i < cartArr.length; i++) {
				let idItem = cartArr[i].good_id;
				let countItem = parseInt(cartArr[i].good_count);
				if(idParam == idItem){
					//数组里有id count加1
					console.log('已经存在该商品---------')
					console.log('------i:',i,'----cartArr[i]:',cartArr[i])
					cartArr[i].good_count = countItem+count;
					isExsit = true;
				}
			}
		}
		//数组里没找到id 添加一条
		if(!isExsit){
			cartArr.push(cart)
		}
		return cartArr;
		
		
	}
	//删除一条
	delArr(cartArr,idParam){
		
		cartArr.splice(cartArr.findIndex(item => item.good_id === idParam), 1)
		return cartArr;
		
		
	}
	
	
	
}


export default new Cart;